﻿using Sasc.PV.BLL;
using Sasc.PV.Common;
using Sasc.PV.Common.DEncrypt;
using Sasc.PV.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sasc.PV.Web.Account
{
    public partial class Login : PVPage
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            //判断系统的IP限制
            AuthorizeByIP();

            //需要真正清空登录用户时，请启用下面这句代码。考虑到部分用户不需要真正清空用户信息，只是转回登陆页。此处，留待自定义启用
            //PublicMethod.SetSessionValue("UserName", null);
            //验证序列号是否正确
            if (!Page.IsPostBack)
            {
                var activateURL = WebUtils.MakeRelative(WebUtils.ActivatePageURL);
                var erpSerils = new ERPSerils();
                if (!erpSerils.ValidateSerilsMatch())
                {
                    //如果是使用无线网卡的电脑，或者是开发时候，以及系统权限不足时，请注释掉下面一行代码。
                    MessageBox.ShowAndRedirect(this, "系统授权码验证无效！请联系周玉偈重新获取授权！", activateURL);
                }

                //时间字符串-----------------------------------------------------------------------------
                if (!erpSerils.ValidateSerilsExpired())
                {
                    //使用时间到达
                    MessageBox.ShowAndRedirect(this, "系统授权码过期！请联系周玉偈重新获取授权！", activateURL);
                }

                if (!string.IsNullOrEmpty(LoginUserName) && !string.IsNullOrEmpty(Context.User.Identity.Name))
                {
                    var backURL = Request["ReturnUrl"];
                    if (!string.IsNullOrEmpty(backURL))
                        Response.Redirect(backURL);
                    else
                        Response.Redirect(WebUtils.AdminPageURL);
                }
            }
        }
        #endregion

        #region Helper Methods
        private void AuthorizeByIP()
        {
            string NowIPStr = Utils.GetIPAddress();//访问者IP
            string[] OAIPArray = WebUtils.AllowedIP.ToString().Trim().Split('|');//允许的IP字符串组数组 
            if (OAIPArray.Any(c => PublicMethod.StrIFIn(c, NowIPStr) || c == "*"))
                return;

            //执行到最后，不允许访问！
            this.TxtUserName.Enabled = false;
            this.TxtUserPwd.Enabled = false;
            this.ImageButton1.Enabled = false;

            MessageBox.Show(this, "您的访问IP不在系统允许范围内，您不能登录系统，请联系管理员！");
        }
        #endregion

        #region Event Handlers
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            string IFPop = "否";
            if (this.CheckBox1.Checked == true)
            {
                IFPop = "是";
            }

            var adminURL = WebUtils.AdminPageURL;
            ERPUser loginUser = new ERPUser();
            var success = false;
            var dataRow = loginUser.UserLogin(TxtUserName.Text.Trim(), DESEncrypt.Encrypt(TxtUserPwd.Text), WebUtils.OALoginType, out success);
            if (dataRow == null)
            {
                System.Web.HttpContext.Current.Response.Write("<script language='javascript'>alert('您所输入的用户名不存在！');</script>");
            }
            else
            {
                if (success)
                {
                    if (DataValidate.ValidateDataRow_S(dataRow, "IfLogin").Trim() == "是")
                    {
                        var userID = DataValidate.ValidateDataRow_S(dataRow, "ID");
                        ConfigurationHelper.SetSession("UserID", userID);
                        ConfigurationHelper.SetSession("UserName", DataValidate.ValidateDataRow_S(dataRow, "UserName"));
                        ConfigurationHelper.SetSession("JiaoSe", DataValidate.ValidateDataRow_S(dataRow, "JiaoSe"));
                        ConfigurationHelper.SetSession("Department", DataValidate.ValidateDataRow_S(dataRow, "Department"));
                        ConfigurationHelper.SetSession("TrueName", DataValidate.ValidateDataRow_S(dataRow, "TrueName"));
                        ConfigurationHelper.SetSession("ZhiWei", DataValidate.ValidateDataRow_S(dataRow, "ZhiWei"));
                        ConfigurationHelper.SetSession("QuanXian", new ERPJiaoSe().GetQuanxian(DataValidate.ValidateDataRow_S(dataRow, "JiaoSe").Replace(",", "','")));

                        FormsAuthentication.SetAuthCookie(userID, false);

                        if (IFPop == "否")
                        {
                            //系统跳转
                            System.Web.HttpContext.Current.Response.Redirect(adminURL);
                        }
                        else
                        {
                            System.Web.HttpContext.Current.Response.Write("<script language=javascript>window.open ('" + adminURL + "','_blank', 'width='+screen.availWidth+',height='+screen.availHeight-20+', left=0,top=0,toolbar=no, menubar=no, scrollbars=no,location=no, status=no') ;window.opener='';window.close();</script>");
                        }
                    }
                    else
                    {
                        System.Web.HttpContext.Current.Response.Write("<script language='javascript'>alert('该用户暂时不允许登陆系统，请联系管理员！');</script>");
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Response.Write("<script language='javascript'>alert('该用户名对应的密码错误！');</script>");
                }
            } 
        }
        #endregion
    }
}